﻿using System.Collections.Generic;
using System.Web;

namespace Transport
{
    public class ShoppingCart
    {

        public List<CartItem> Items { get; private set; }
        public static readonly ShoppingCart Instance;
        static ShoppingCart()
        {

            if (HttpContext.Current.Session["ShoppingCart"] == null)
            {
                Instance = new ShoppingCart();
                Instance.Items = new List<CartItem>();
                HttpContext.Current.Session["ShoppingCart"] = Instance;
            }
            else
            {
                Instance = (ShoppingCart)HttpContext.Current.Session["ShoppingCart"];
            }
        }

        protected ShoppingCart() { }
         public int GetCountCart()
        {
            return Items.Count;
        }
        public void AddItem(CartDTO cartinfo)
        {

            CartItem newItem = new CartItem(cartinfo);

            if (Items.Count == 0 || Items[0].CarInfo.MaDichVu == newItem.CarInfo.MaDichVu)
            {
                if (Items.Contains(newItem))
                {
                    foreach (CartItem item in Items)
                    {
                        if (item.Equals(newItem))
                        {
                            item.CarInfo.Mien = newItem.CarInfo.Mien;
                            item.CarInfo.PhuongThucLai = newItem.CarInfo.PhuongThucLai;
                        }
                    }
                }
                else
                {
                    Items.Add(newItem);
                }
            }
        }

        public void RemoveItem(string maXe)
        {
            int index = -1;
            for (int i = 0; i < Items.Count; i++)
            {
                if (Items[i].CarID == maXe)
                {
                    index = i;
                    break;
                }
            }
            if(index != -1)
                Items.RemoveAt(index);
            
        }
        public void RemoveAllItem()
        {
            for (int i = 0; i < Items.Count; i++)
            {
                Items.RemoveAt(i);
            }

        }
        public decimal GetSubTotal()
        {
            decimal subTotal = 0;
            foreach (CartItem item in Items)
                subTotal += item.TotalPrice;

            return subTotal;
        }
    }
}
